package com.cl.blog.web.client.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cl.blog.document.ContentAndUser;
import com.cl.blog.entity.BContent;
import com.cl.blog.service.BContentService;
import com.cl.blog.service.BUserService;
import com.cl.blog.util.RedisUtil;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.stream.RecordId;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author 付
 * @Date 2024-04-02 12:22
 * @Version 1.0
 * @description 处理历史浏览持久化的定时任务
 * @since 1.0
 */
public class LikeTask extends QuartzJobBean {
	@Autowired
	BUserService bUserService;
	@Autowired
	BContentService bContentService;

	@Autowired
	RedisUtil redisUtil;

	/**
	 * 用来从redis中的hash中获取浏览量缓存的键值对，间隔时间存入mysql
	 *
	 * @param context
	 * @throws JobExecutionException
	 */
	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		// 要执行的内容就写在这个函数中
		//获取所有的文章数据
		List<BContent> list = bContentService.list(new QueryWrapper<BContent>()
				.eq("status", 2)
				.eq("is_delete", 0)
		);
		// 获取文章id和用户id
		List<ContentAndUser> collect = list.stream()
				.map(bContent ->
						new ContentAndUser(bContent.getUserId(), bContent.getId()))
				.collect(Collectors.toList());
		// 文章id-浏览量
		Map<Integer, Integer> map = new HashMap<>();
		// 获取缓存的数据
		for (ContentAndUser contentAndUser : collect) {
			String key = contentAndUser.getUserId() + "-" + contentAndUser.getContentId() + "-history";
			System.out.println(key + "---" + key.isEmpty());
			String s = redisUtil.get(key);
			if (s != null) {
				Integer o = Integer.valueOf(s);
				if (o == null) {
					map.put(contentAndUser.getContentId(), 0);
				} else {
					map.put(contentAndUser.getContentId(), o);
				}
				redisUtil.delete(key);
			}
		}
		System.out.println("持久的数据集合-->" + map);
		if (map.size() <= 0) {
			return;
		}
		// 将对应的数据存储到数据库
		for (BContent bContent : list) {
			if (map.get(bContent.getId()) != null) {
				bContent.setHistoryPeopleCount(Long.valueOf(map.get(bContent.getId())) + bContent.getHistoryPeopleCount());
			}
		}
		bContentService.updateBatchById(list);
	}
}

